package pers.cz.request;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * 公共请求方法（包含post、get）
 * @program: PostGirl-panent
 * @description: RequestAndResponse
 * @author: Cheng Zhi
 * @create: 2021-03-10 09:17
 **/
public class RequestReturnResponse {

    /**
     * 通过post请求调用外部接口
     * @param request 请求json字符串
     * @param url 请求地址
     * @return
     */
    public static String getResultByPost(String request, String url) {

        HttpPost post = new HttpPost(url);
        // 设置header部分信息
        post.setHeader("content-type","application/json");
        // 设置入参
        // 判断入参中是否包含参数化标识符，如果包含，则将标识符替换为自定义标识

        StringEntity entity = new StringEntity(request,"utf-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        // 执行请求
        String result = "";
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        try {
            HttpResponse response  = defaultHttpClient.execute(post);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * 通过get请求调用外部接口
     * @param request 请求入参
     * @param url 请求地址
     * @return
     */
    public static String getResultByGet(String request, String url) {

        String result = "";
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求的参数

        try {
            url = url + "?" + request;
            URI uri = new URIBuilder(url).build();
            HttpGet get = new HttpGet(uri);
            HttpResponse response = httpclient.execute(get);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        getResultByGet(null,"http://localhost:90/queryTestCase/queryAllTestCase");
    }
}
